package com.core.website.scheduled;

import com.core.website.entity.Content;
import com.core.website.mapper.ContentMapper;
import com.core.website.service.ContentService;
import com.core.website.util.SpringUtil;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Component
public class SaticScheduleTask {

    private ContentMapper contentMapper;
    private ContentService contentService;
    @Scheduled(cron = "0 0 */1 * * ?")
    public void configureTasks() {
        if(null==contentMapper){
            contentMapper=SpringUtil.getBean(ContentMapper.class);
        }
        if(null==contentService){
            contentService=SpringUtil.getBean(ContentService.class);
        }
        List<Content> contents = contentMapper.queryNewAll();
        if(null!=contents&&contents.size()>0){
            List<String> unNewIdList=new ArrayList<>();
            for(Content  content:contents){
                if("1".equals(content.getNewContent())){
                    int differHour = getDifferHour(content.getApprovalTime(), new Date());
                    if(differHour>=24){
                        unNewIdList.add(content.getId());
//                        contentService.unNew(content.getId());
                    }
                }
            }
            if(unNewIdList.size()>0){
                if(unNewIdList.size()>1000){
                    int max=0;
                    if(unNewIdList.size()%1000>0){
                         max=(unNewIdList.size()/1000)+1;
                    }else{
                        max=(unNewIdList.size()/1000);
                    }
                    for(int i=0;i<max;i++){
                        List<String> strings=new ArrayList<>();
                        if((i + 1) * 1000<unNewIdList.size()){
                            strings = unNewIdList.subList(i * 1000, (i + 1) * 1000);
                        }else{
                            strings = unNewIdList.subList(i * 1000, unNewIdList.size());
                        }
                        contentService.unNew(strings);
                    }
                }else{
                    contentService.unNew(unNewIdList);
                }

            }
        }

    }
    // 24 * (differ / dayM) 这里拿到被舍弃的整数，整数是几，就代表相隔几天，一天24小时，那就整数乘以24即可。
    private static int getDifferHour(Date startDate, Date endDate) {
        long dayM = 1000 * 24 * 60 * 60;
        long hourM = 1000 * 60 * 60;
        long differ = endDate.getTime() - startDate.getTime();
        long hour = differ % dayM / hourM + 24 * (differ / dayM);
        return Integer.parseInt(String.valueOf(hour));
    }
}